//
//  StatisticsView.m
//  VivaModa
//
//  Created by Sergey on 3/4/13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "StatisticsView.h"
#import "statistics_balans_cell.h"
#import "statistics_purchace.h"
#import "statistics_my_friend_cell.h"

@interface StatisticsView ()
@property(nonatomic,retain) UILabel *title_label;
@end

@implementation StatisticsView
@synthesize title_name;
@synthesize title_label;
@synthesize tableView;
@synthesize infoData;
@synthesize connection;
@synthesize statisticsType;
@synthesize infoAboutOrders;
@synthesize needReload;

NSArray *array_stattistic_data;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self addCustomBackButton];
    self.view.backgroundColor = [Singleton sharedMySingleton].backgroundTableView;
    
    self.title_label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 140, 44)];
    self.title_label.backgroundColor = [UIColor clearColor];
    self.title_label.font = [UIFont fontWithName:@"Arial" size:14];
    self.title_label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    self.title_label.textAlignment = UITextAlignmentCenter;
    self.title_label.textColor = [UIColor whiteColor]; // change this color
    self.title_label.numberOfLines = 2;
    self.navigationItem.titleView = self.title_label;
}



-(void)viewWillAppear:(BOOL)animated{
    
    
    
    if (needReload) {
        array_stattistic_data = nil;
        [self.tableView reloadData];
        self.title_label.text = title_name;
        [self parseStatistics:self.statisticsType];
        needReload = NO;
    }
    
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [connection cancel];
}





#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [array_stattistic_data count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    switch (self.statisticsType) {
        case statistic_my_balans:{
            static NSString *CellIdentifier = @"statistics_balans_cell";
            statistics_balans_cell *cell = nil;
            cell = (statistics_balans_cell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(!cell)
            {
                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"statistics_balans_cell" owner:nil options:nil];
                for(id currentObject in topLevelObjects)
                {
                    if([currentObject isKindOfClass:[statistics_balans_cell class]])
                    {
                        cell = (statistics_balans_cell *)currentObject;
                        break;
                    }
                }
            }
            
            cell.date.text = [self getTextFromArrayWithKey:@"date" index:indexPath.row];
            
            cell.customer_name.text = [self getTextFromArrayWithKey:@"customer_name" index:indexPath.row];
            
            cell.current_balance.text = [self getTextFromArrayWithKey:@"balance" index:indexPath.row];
            
            cell.commision.text = [self getTextFromArrayWithKey:@"commission" index:indexPath.row];
            
            cell.plus_bonus.text = [self getTextFromArrayWithKey:@"bonus+" index:indexPath.row];
            
            cell.minus_bonus.text = [self getTextFromArrayWithKey:@"bonus-" index:indexPath.row];
            
            cell.emount.text = [self getTextFromArrayWithKey:@"amount" index:indexPath.row];
            
            cell.number_order.text = [self getTextFromArrayWithKey:@"number" index:indexPath.row];
            
            UIView *bg_sel = [[UIView alloc] initWithFrame:cell.bounds];
            bg_sel.backgroundColor = [UIColor clearColor];
            cell.selectedBackgroundView = bg_sel;
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            return cell;
            break;}
            
        case statistic_my_purchace:{
            static NSString *CellIdentifier_2 = @"statistics_purchace";
            statistics_purchace *cell_2 = nil;
            cell_2 = (statistics_purchace *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier_2];
            if(!cell_2)
            {
                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"statistics_purchace" owner:nil options:nil];
                for(id currentObject in topLevelObjects)
                {
                    if([currentObject isKindOfClass:[statistics_purchace class]])
                    {
                        cell_2 = (statistics_purchace *)currentObject;
                        break;
                    }
                }
            }
            
            cell_2.date.text = [self getTextFromArrayWithKey:@"date" index:indexPath.row];
            
            cell_2.customer_name.text = [self getTextFromArrayWithKey:@"customer_name" index:indexPath.row];
            
            cell_2.current_balance.text = [self getTextFromArrayWithKey:@"balance" index:indexPath.row];
            
            cell_2.commision.text = [self getTextFromArrayWithKey:@"commission" index:indexPath.row];
            
            cell_2.plus_bonus.text = [self getTextFromArrayWithKey:@"bonus+" index:indexPath.row];
            
            cell_2.minus_bonus.text = [self getTextFromArrayWithKey:@"bonus-" index:indexPath.row];
            
            cell_2.emount.text = [self getTextFromArrayWithKey:@"amount" index:indexPath.row];
            
            cell_2.number_order.text = [self getTextFromArrayWithKey:@"number" index:indexPath.row];
            
            cell_2.status.text = [self getTextFromArrayWithKey:@"status" index:indexPath.row];
            
            UIView *bg_sel = [[UIView alloc] initWithFrame:cell_2.bounds];
            bg_sel.backgroundColor = [UIColor clearColor];
            cell_2.selectedBackgroundView = bg_sel;
            
            cell_2.selectionStyle = UITableViewCellSelectionStyleGray;
            
            
            return cell_2;
            
            break;}
        case statistic_my_friend:{
            
            static NSString *CellIdentifier_3 = @"statistics_my_friend_cell";
            statistics_my_friend_cell *cell_3 = nil;
            cell_3 = (statistics_my_friend_cell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier_3];
            if(!cell_3)
            {
                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"statistics_my_friend_cell" owner:nil options:nil];
                for(id currentObject in topLevelObjects)
                {
                    if([currentObject isKindOfClass:[statistics_my_friend_cell class]])
                    {
                        cell_3 = (statistics_my_friend_cell *)currentObject;
                        break;
                    }
                }
            }
            
            cell_3.date.text = [self getTextFromArrayWithKey:@"date" index:indexPath.row];
            
            cell_3.customer_name.text = [self getTextFromArrayWithKey:@"customer_name" index:indexPath.row];
            
            cell_3.emount.text = [self getTextFromArrayWithKey:@"amount" index:indexPath.row];
            
            cell_3.commision.text = [self getTextFromArrayWithKey:@"commission" index:indexPath.row];
            
            cell_3.earned.text = [self getTextFromArrayWithKey:@"balance" index:indexPath.row];
            
            
            UIView *bg_sel = [[UIView alloc] initWithFrame:cell_3.bounds];
            bg_sel.backgroundColor = [UIColor clearColor];
            cell_3.selectedBackgroundView = bg_sel;
            
            cell_3.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell_3;
            break;}
        default:
            break;
    }
    
    
    
    
}


-(NSString*)getTextFromArrayWithKey:(NSString*)key index:(int)index_array{
    NSString* text = [[array_stattistic_data objectAtIndex:index_array] objectForKey:key];
    if(text==(id) [NSNull null] || [text isEqual:[NSNull null]])
    {
        return @"";
    }else{
        return [NSString stringWithFormat:@"%@",text];
    }
}



- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (self.statisticsType) {
        case statistic_my_balans:{
            return 142;}
            break;
        case statistic_my_purchace:{
            return 159;}
        case statistic_my_friend:{
            return 91;}
        default:
            return 142;
            break;
    }
    
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.statisticsType == statistic_my_purchace) {
        if (!infoAboutOrders) {
            infoAboutOrders = [[InfoAboutOrders alloc] initWithNibName:@"InfoAboutOrders" bundle:nil];
        }
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        //NSLog(@"array = %@",array_stattistic_data);
        infoAboutOrders.order_number = [[[array_stattistic_data objectAtIndex:indexPath.row] objectForKey:@"number"] integerValue];
        [self.navigationController pushViewController:infoAboutOrders animated:YES];
    }
}




#pragma mark Dejal activity

- (void)displayActivityView
{
    //[self removeActivityView];
    
    if ([DejalActivityView isActive]) {
        return;
    }
    
    UIView *viewToUse = self.tabBarController.tabBar.superview;
    [DejalBezelActivityView activityViewForView:viewToUse];
    [DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
    [DejalActivityView currentActivityView].activityLabel.text = @"Синхронизация";
    //[self performSelector:@selector(removeActivityView) withObject:nil afterDelay:3.0];
}

- (void)removeActivityView;
{
    [DejalBezelActivityView removeViewAnimated:YES];
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark



-(void)parseStatistics:(statistics_type)statistic_type{
    NSURL* url;
    switch (self.statisticsType) {
        case statistic_my_balans:{
            url = [NSURL URLWithString:[NSString stringWithFormat:@"http://moda.viva-viva.ru/mobile/statistics.php?id_customer=%i&stat_type=bonus",[Singleton sharedMySingleton].user_id]];
            break;}
        case statistic_my_purchace:{
            //495
            //329
            url = [NSURL URLWithString:[NSString stringWithFormat:@"http://moda.viva-viva.ru/mobile/statistics.php?id_customer=%i&stat_type=account",[Singleton sharedMySingleton].user_id]];
            break;}
        case statistic_my_friend:{
            url = [NSURL URLWithString:[NSString stringWithFormat:@"http://moda.viva-viva.ru/mobile/statistics.php?id_customer=%i&stat_type=ref",[Singleton sharedMySingleton].user_id]];
            break;}
        default:
            return;
            break;
    }
    
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection) {
        self.infoData = nil;
        self.infoData = [NSMutableData data];
    }
}




- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [self removeActivityView];
    [self showNoInternetAlert];
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [infoData appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{
    //NSString *result = [[NSString alloc] initWithData:infoData encoding:NSUTF8StringEncoding];
    //NSLog(@"result = %@", result);
    [self parseJSON:infoData];
}


#pragma mark parse JSON result

-(void)parseJSON:(NSData*)data{
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          
                          JSONObjectWithData:data
                          
                          options:kNilOptions
                          
                          error:&error];
    
    NSString* requestResultAutorization = [json objectForKey:@"success"];
    
    
    if (self.statisticsType== statistic_my_purchace){
        
       
        
        if ([requestResultAutorization integerValue]==1) {
            
            NSDictionary * dict_data;;
            NSArray *array_data;
            bool is_dict = NO;;
            id item = [json objectForKey:@"message"];
            if ([item isKindOfClass:[NSArray class]]) {
                is_dict = NO;
                array_data = [json objectForKey:@"message"];
            }
            else if ([item isKindOfClass:[NSDictionary class]]) {
                dict_data = [json objectForKey:@"message"];
                is_dict = YES;
            }
            
            
            if (is_dict) {
                // это словарь, его конвертнем в массив
                NSArray *keyDict = [dict_data allKeys];
                NSMutableArray *tempArray = [[NSMutableArray alloc] initWithCapacity:1];
                
                for (int i = 0 ; i < [keyDict count]; i++) {
                    NSDictionary *dict = [dict_data objectForKey:[keyDict objectAtIndex:i]];
                    [tempArray addObject:dict];
                }
                
                array_stattistic_data = tempArray;
                
            }else{
               // это массив
               array_stattistic_data = array_data;
            }
            [self.tableView reloadData];
        }else{
            if (![[json objectForKey:@"message"] isEqualToString:@"Empty"]) {
                BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Ошибка синхронизации"];
                [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                    
                }];
                [alert show];
            }
            
        }
    }else{
        NSArray * array = [json objectForKey:@"message"];
        if ([requestResultAutorization integerValue]==1) {
            
            
            NSDictionary * dict_data;;
            NSArray *array_data;
            bool is_dict = NO;;
            id item = [json objectForKey:@"message"];
            if ([item isKindOfClass:[NSArray class]]) {
                is_dict = NO;
                array_data = [json objectForKey:@"message"];
            }
            else if ([item isKindOfClass:[NSDictionary class]]) {
                dict_data = [json objectForKey:@"message"];
                is_dict = YES;
            }

            
            if (is_dict) {
                // это словарь, его конвертнем в массив
                NSArray *keyDict = [dict_data allKeys];
                NSMutableArray *tempArray = [[NSMutableArray alloc] initWithCapacity:1];
                
                for (int i = 0 ; i < [keyDict count]; i++) {
                    NSDictionary *dict = [dict_data objectForKey:[keyDict objectAtIndex:i]];
                    [tempArray addObject:dict];
                }
                
                array_stattistic_data = tempArray;
                
            }else{
                // это массив
                array_stattistic_data = array_data;
            }

      
            
            [self.tableView reloadData];
        }else{
            if (![[json objectForKey:@"message"] isEqualToString:@"Empty"]) {
                BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Ошибка синхронизации"];
                [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                    
                }];
                [alert show];
                
            }
            
        }
    }
    
    
    
    [self removeActivityView];
}


- (void)showNoInternetAlert
{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка Internet соединения" message:@"Для работы с магазином необходимо подключение к сети Internet. Пожалуйста, проверте подключение к сети и повторите попытку."];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        [UserDefaults setObject:@"NO" forKey:@"SuccsesUpdateCategories"];
        [self removeActivityView];
    }];
    //[alert setDestructiveButtonWithTitle:@"Повторить" block:nil];
    [alert addButtonWithTitle:@"Повторить " block:^{
        //[self displayActivityView];
        [self performSelector:@selector(parseCategories) withObject:nil afterDelay:1.0];
        //[self parseCategories];
    }];
    [alert show];
}


-(BOOL)InternetConnection{
    internetReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [internetReach currentReachabilityStatus];
    if (netStatus == ReachableViaWiFi || netStatus == ReachableViaWWAN) {
        return YES;
    }else{
        return NO;
    }
    
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)addCustomBackButton{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 65, 29)];
    //[backButton setImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) ] forState:UIControlStateNormal];
    
    [backButton setBackgroundImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(8, 20, 20, 20) ] forState:UIControlStateNormal];
    
    [backButton setTitle:@" Назад" forState:UIControlStateNormal];
    [backButton.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
    
    [backButton setShowsTouchWhenHighlighted:NO];
    [backButton addTarget:self action:@selector(popViewControllerWithAnimation) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBackItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.hidesBackButton = TRUE;
    self.navigationItem.leftBarButtonItem = barBackItem;
}

-(void)popViewControllerWithAnimation{
    [self.navigationController popViewControllerAnimated:YES];
}


@end
